<%-- 
    Document   : index
    Created on : Feb 15, 2012, 2:05:59 PM
    Author     : Saeed
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.io.IOException"%>
<%@page import="java.io.FileInputStream"%>
<%@page import="java.io.File"%>

<%! 
/**
 *
 * @author Saeed
 */

    String readSrc(String filePath) throws IOException {
        File file = new File(filePath); //creating a file instance to work with
        int ch; //holds bytes of data from the file being read
        StringBuffer strContent = new StringBuffer(""); //create the buffer
        try {
            FileInputStream fin = new FileInputStream(file);  //open an input connection to the file
            while ((ch = fin.read()) != -1) {                //not the end of file yet?
                strContent.append((char) ch); //append bytes to the string which carries the whole file.
            }
            fin.close(); //end if file. close the connection.
        } catch (Exception ex) {
            //Logger.getLogger(ReadDitaFile.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("An error happened: " + ex);
        }
        String fileContent = strContent.toString();
        return (fileContent); //print out the file content.
    }

%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8">
        <title>Code Editor</title>
        <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.9.0/build/assets/skins/sam/skin.css">
        <!-- Core + Skin CSS -->
        <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.9.0/build/button/assets/skins/sam/button.css">
        <!-- OPTIONAL: Menu Stylesheet (required for creating buttons of type "menu" and "split") -->
        <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.9.0/build/menu/assets/skins/sam/menu.css">

        <!-- Utility Dependencies -->
        <script src="http://yui.yahooapis.com/2.9.0/build/yahoo-dom-event/yahoo-dom-event.js"></script> 
        <script src="http://yui.yahooapis.com/2.9.0/build/element/element-min.js"></script> 
        <!-- Needed for Menus, Buttons and Overlays used in the Toolbar -->
        <script src="http://yui.yahooapis.com/2.9.0/build/container/container_core-min.js"></script>
        <script src="http://yui.yahooapis.com/2.9.0/build/menu/menu-min.js"></script>
        <script src="http://yui.yahooapis.com/2.9.0/build/button/button-min.js"></script>
        <!-- Source file for Rich Text Editor-->
        <script src="http://yui.yahooapis.com/2.9.0/build/editor/editor-min.js"></script>
        <!--there is no custom header content for this example-->
        <script src="http://yui.yahooapis.com/2.9.0/build/dragdrop/dragdrop-min.js" ></script>
        <script src="http://yui.yahooapis.com/2.9.0/build/tabview/tabview-min.js"></script>
        <script src="http://yui.yahooapis.com/2.9.0/build/container/container-min.js"></script>

        <style type="text/css">
            .yui-skin-sam .yui-toolbar-container .yui-toolbar-ditaTag span.yui-toolbar-icon {
                background-image: url(img/y_icon.gif);
                background-position: 1px 0px;
            }

            .yui-skin-sam .yui-toolbar-container .yui-toolbar-editcode span.yui-toolbar-icon {
                background-image: url(img/html_editor.gif);
                background-position: 0 1px;
                left: 5px;
            }
            .yui-skin-sam .yui-toolbar-container .yui-button-editcode-selected span.yui-toolbar-icon {
                background-image: url(img/html_editor.gif );
                background-position: 0 1px;
                left: 5px;
            }
            .editor-hidden {
                visibility: hidden; 
                top: -9999px;
                left: -9999px;
                position: absolute;
            }
            textarea {
                border: 0;
                margin: 0;
                padding: 0;
            } 
        </style>
        <script>
            (function() { 
                //Setup some private variables 
                var Dom = YAHOO.util.Dom, 
                Event = YAHOO.util.Event; 
	 
                //The Editor config 
                var myConfig = { 
                    height: '300px', 
                    width: '600px', 
                    animate: true, 
                    dompath: true,
                    markup: 'xhtml',
                    focusAtStart: true,
                    handleSubmit: true
                }; 
                // setting state for code editor
                var state = 'off';
                YAHOO.log('Set state to off..', 'info', 'example');  //?

                //Now let's load the Editor.. 
                var myEditor = new YAHOO.widget.Editor('kmdoc', myConfig);
             
                // Code Editor chunk
                myEditor.on('toolbarLoaded', function() {
                    //Inside the toolbarLoaded event
                    this.toolbar.on('editcodeClick', function() {
                        var ta = this.get('element'),
                        iframe = this.get('iframe').get('element');

                        if (state == 'on') {
                            state = 'off';
                            this.toolbar.set('disabled', false);
                            YAHOO.log('Show the Editor', 'info', 'example');
                            YAHOO.log('Inject the HTML from the textarea into the editor', 'info', 'example');
                            this.setEditorHTML(ta.value);
                            if (!this.browser.ie) {
                                this._setDesignMode('on');
                            }

                            Dom.removeClass(iframe, 'editor-hidden');
                            Dom.addClass(ta, 'editor-hidden');
                            this.show();
                            this._focusWindow();
                        } else {
                            state = 'on';
                            YAHOO.log('Show the Code Editor', 'info', 'example');
                            this.cleanHTML();
                            YAHOO.log('Save the Editors HTML', 'info', 'example');
                            Dom.addClass(iframe, 'editor-hidden');
                            Dom.removeClass(ta, 'editor-hidden');
                            this.toolbar.set('disabled', true);
                            this.toolbar.getButtonByValue('editcode').set('disabled', false);
                            this.toolbar.selectButton('editcode');
                            this.dompath.innerHTML = 'Editing HTML Code';
                            this.hide();
                        }
                        return false;
                    }, this, true);
                    this.on('cleanHTML', function(ev) {
                        YAHOO.log('cleanHTML callback fired..', 'info', 'example');
                        this.get('element').value = ev.html;
                    }, this, true);
                    this.on('afterRender', function() {
                        var wrapper = this.get('editor_wrapper');
                        wrapper.appendChild(this.get('element'));
                        this.setStyle('width', '100%');
                        this.setStyle('height', '100%');
                        this.setStyle('visibility', '');
                        this.setStyle('top', '');
                        this.setStyle('left', '');
                        this.setStyle('position', '');

                        this.addClass('editor-hidden');
                    }, this, true);
                    
                }, myEditor, true);
                
                //Adding button for HTML editor toggler
                myEditor.on('toolbarLoaded', function() {
                    var codeConfig = {
                        type: 'push', label: 'Edit HTML Code', value: 'editcode'
                    };
                    YAHOO.log('Create the (editcode) Button', 'info', 'example');
                    this.toolbar.addButtonToGroup(codeConfig, 'insertitem');

                    this.on('afterRender', function() {
                        //snipped
                    }, this, true);
                }, myEditor, true);

                myEditor.on('toolbarLoaded', function() {       
                    var ditaTag = {
                        showDlg : false, dlg : null, 
                        dialog_config : { width: '300px', height: 'auto', fixedcenter: true, constraintoviewport: true, visible: false, draggable: true, modal: true },
                        handleCancel : function() {
                            // If the user clicked cancel in the dialog, then hide the dialog
                            this.cancel();
                            ditaTag.showDlg = false;
                        },         
                        handleSubmit : function() {
                            // If the user clicked submit, then insert the xref HTML into the editor 
                            if (!this.getData().href && !this.getData().scope && !this.getData().xref) return false;
                            ditaTag.showDlg = false;
      
                            var href = this.getData().href, 
                            scope = this.getData().scope,
                            xref = this.getData().xref,
                            xrefTag = '';
                            
                            xrefTag = '<xref href=' + '"'+ href + '" ' + 'scope="' + scope + '">'+xref+'</xref>';
                            /*
                            if (href) address += '"'+ href + '" ';
                            if (scope) address += 'scope="' + scope + '"';
                             */                
                            // Create the HTML code to insert the dita tag into the editor
//                            var html = xrefTag;
                            // Insert the html into the editor
                            myEditor.execCommand('inserthtml', xrefTag);
                            // Hide the dialog
                            this.cancel();
                            
                            //This piece of code moves the cursor to the end of inserted element.
                            var pos = 1000; //pos determines where to place the cursor. if greater than the length of characters, it will place at the end.
                            if(myEditor.createTextRange) { //IE Specific code
                                var range = myEditor.createTextRange();   
                                range.move("character", pos);   
                                range.select();   
                            } else if(myEditor.selectionStart) {  //Works with Firefox and other browsers 

                                myEditor.focus();   
                                myEditor.setSelectionRange(pos, pos);   
                            }  
                            myEditor.focus(); 
                        }, 
                        createDialog: function() {
                            // Create the container element for the dialog
                            var ditatagEle = document.createElement('div');          
                            ditatagEle.setAttribute('id', 'youTubeDlg');
                            ditatagEle.innerHTML = '<div class="hd">Insert dita Tag (xref)</div><div class="bd"><form name="ditaForm" class="text"><table><tr><td>href</td><td><input type="text" name="href" /></td></tr><tr><td>scope</td><td><input type="text" name="scope" /></td></tr><tr><td>xref</td><td><input type="text" name="xref" /></td></tr></table></form></div>';
                            YAHOO.util.Dom.setStyle(ditatagEle, 'visibility', 'hidden');
                            document.body.appendChild(ditatagEle);
                            // Create the dialog                    
                            ditaTag.dlg = new YAHOO.widget.Dialog(ditatagEle, ditaTag.dialog_config);
                            ditaTag.dlg.cfg.queueProperty("buttons", [ { text:"Submit", handler:ditaTag.handleSubmit, isDefault:true }, { text:"Cancel", handler:ditaTag.handleCancel } ]);
                            ditaTag.dlg.render(document.body);
                        },         
                        toggle : function() {
                            // Show/Hide the ditaTag dialog
                            ditaTag.showDlg = !ditaTag.showDlg;
                            if (ditaTag.showDlg) {           
                                ditaTag.dlg.show();
                            } else {           
                                ditaTag.dlg.hide();
                            }
                        }
                    };        
                    // Add the dita Tag button to the editor's toolbar in the Insert Item group
                    myEditor.toolbar.addButtonToGroup({ type: 'push', label: 'Insert dita tag', value: 'ditaTag' }, 'insertitem');                
                    // When the user clicks the button, then run this function
                    myEditor.toolbar.on('ditaTagClick', function() {
                        ditaTag.toggle();
                    });        
                    // Create the dialog that allows the user to enter the dita tag
                    ditaTag.createDialog();       
                });
                // end of copied text
                
                myEditor.render();
            })(); 
        </script>
    </head>
    <body class="yui-skin-sam">
        <h1>Code Editor</h1>
        <form name="editor" method="POST" action="testServlet" >
            <textarea name="kmdocument" id="kmdoc" cols="50" rows="10">
                <% out.println(readSrc("C:/Users/Saeed/Downloads/mydoc.dita")); %>
            </textarea>
            Save as a text file with this name: <input name="fileName" size="20" type="text"/>
            <input type="submit" value="Save"/>
        </form>

    </body>
</html>
